package top.csy8888.ch03;

import com.rabbitmq.client.*;

/**
 * @author CSY
 * @date 2025 - 10 - 10
 */
public class ConsumerA {
    /**
     * 自定义队列名称
     */
    private static final String QUEUE_ONE = "queue.topic.one";

    /**
     * 自定义交换机名称
     */
    private static final String EXCHANGE_NAME = "my.topic";

    private static final ConnectionFactory connectionFactory;

    static {
        connectionFactory = new ConnectionFactory();

        connectionFactory.setHost("127.0.0.1");

        connectionFactory.setPort(5672);

        connectionFactory.setUsername("csy");

        connectionFactory.setPassword("csy11348336");
    }

    /**
     * 接收消息
     */
    public static void receive(){
        try{
            Connection conn = connectionFactory.newConnection();
            Channel channel = conn.createChannel();
            //声明交换机
            channel.exchangeDeclare(EXCHANGE_NAME, BuiltinExchangeType.TOPIC);
            //声明队列
            channel.queueDeclare(QUEUE_ONE, false, false, false, null);

            //将交换机和队列进行绑定 - 结合路由的key来进行绑定
            // 参数三：路由的key
            channel.queueBind(QUEUE_ONE, EXCHANGE_NAME, "my.*");

            //接收消息
            DeliverCallback deliverCallback = (consumerTag, delivery) -> {
                String message = new String(delivery.getBody(), "UTF-8");
                System.out.println(message);
            };
            channel.basicConsume(QUEUE_ONE, true, deliverCallback, consumerTag -> {});
        }catch (Exception e){
            throw new RuntimeException("消费失败",e);
        }
    }

    public static void main(String[] args) {
        receive();
    }
}
